package com.xiao.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xiao.entity.JiciEntity;
import com.xiao.entity.MemberEntity;
import com.xiao.entity.UserEntity;
import com.xiao.service.JiciService;
import com.xiao.service.MemberService;
import com.xiao.util.XiaoUtils;

import net.sf.json.JSONObject;

@Controller
@RequestMapping("jici")
public class JiciController {

	@Autowired
	private JiciService jiciService;

	@Autowired
	private MemberService memberService;

	@RequestMapping("toJici")
	public String toJici() {
		return "jici/jici";
	}

	@RequestMapping("findAll")
	@ResponseBody
	public JSONObject findAll(JiciEntity jiciEntity) {
		List<JiciEntity> findAll = jiciService.findAllByPager(jiciEntity);
		int count = jiciService.findAllCount();
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("rows", findAll);
		jsonObject.put("total", count);
		return jsonObject;
	}

	@RequestMapping("toInsert")
	public String toInsert() {
		return "jici/insert";
	}

	@RequestMapping("insert")
	@ResponseBody
	public int insert(JiciEntity jiciEntity,HttpServletRequest request) {
		HttpSession session = request.getSession();
		UserEntity user = (UserEntity)session.getAttribute("USER");
		String currentTime = XiaoUtils.getCurrentTimeMes();
		jiciEntity.setJtime(currentTime);
		jiciEntity.setUid(user.getUid());
		jiciService.insert(jiciEntity);
		//修改金额
		MemberEntity findOneByRid = memberService.findOneByRid(jiciEntity.getRid());
		findOneByRid.setRmoney(findOneByRid.getRmoney()-jiciEntity.getJmoney());
		//计算积分
		findOneByRid.setRjf(findOneByRid.getRjf()+jiciEntity.getJmoney()*0.01);
		memberService.update(findOneByRid);
		return 1;

	}

	@RequestMapping("toUpdate")
	public String toUpdate(int jid, Model model) {
		JiciEntity jiciEntity = jiciService.findOneByJid(jid);
		model.addAttribute("ar", jiciEntity);
		return "jici/update";
	}

	@RequestMapping("update")
	@ResponseBody
	public int update(JiciEntity jiciEntity) {
		jiciService.update(jiciEntity);
		return 1;
	}

	@RequestMapping("findAllNoPager")
	@ResponseBody
	public List<JiciEntity> findAllNoPager(){
		return jiciService.findAll();
	}

}
